import os
from openai import OpenAI
from typing import TypedDict
import json  # 添加导入json模块


class Input(TypedDict):
    api_key: str
    image_url: str


class Output(TypedDict):
    text: str
    error_message: str


# def handler(args) -> Output:


def handler(api_key1, image_url1) -> Output:
    try:
        # 从输入参数中获取 API 密钥和图像 URL
        api_key = api_key1
        image_url = image_url1

        # 创建 OpenAI 客户端实例
        client = OpenAI(
            api_key=api_key,  # 使用传入的 API 密钥
            # base_url="https://dashscope.aliyuncs.com/compatible-mode/v1",  # 指定 Base URL
            base_url="https://api.siliconflow.cn/v1/chat/completions",
        )

        # 调用 qwen-vl-plus 模型进行图像识别
        completion = client.chat.completions.create(
            model="Qwen/QwQ-32B",  # "qwen-vl-plus",  # 模型名称
            messages=[
                {
                    "role": "user",
                    "content": [
                        {"type": "text", "text": "这是什么"},  # 提问，问图像内容
                        {
                            "type": "image_url",
                            "image_url": {"url": image_url},
                        },  # 传入图像 URL
                    ],
                }
            ],
        )

        # 打印返回的内容，检查其结构
        result = completion.model_dump_json()
        print("Model response:", result)

        # 将返回的字符串转换为字典
        result_dict = json.loads(result)

        # 获取 content 内容
        text = (
            result_dict.get("choices", [{}])[0]
            .get("message", {})
            .get("content", "无法获取识别结果")
        )

        return {"content": text}

    except Exception as e:
        return {"error_message": str(e)}  # 如果发生错误，返回错误信息


if __name__ == "__main__":
    # 模拟输入参数
    class MockArgs:
        def __init__(self, api_key, image_url):
            self.input = Input(api_key=api_key, image_url=image_url)

    # 替换为您的实际 API 密钥
    api_key = "sk-fzaxlslrehzpfsrcdcadupnqkyrudlwodxircbjchaggxrfd"
    # 替换为您的实际图像 URL
    image_url = "https://static.deepinout.com/gk-static/logo.png"

    args = MockArgs(api_key, image_url)

    # 调用 handler 函数
    # result = handler(args)
    result = handler(api_key, image_url)
    if "error_message" in result:
        print(f"发生错误: {result['error_message']}")
    else:
        print(f"识别结果: {result['text']}")
